#![allow(dead_code)]

use crate::entity::{prelude::*, stock_user};
use sea_orm::{prelude::*, *};

#[derive(Default, Debug)]
pub struct UserSearch {
    uid: Option<i32>,
    username: Option<String>,
    pageindex: u64,
    pagesize: u64,
}

/// 转账
pub async fn update_money_by_transfer(
    db: &DbConn,
    uid: i32,
    money: f64,
) -> Result<stock_user::Model, DbErr> {
    let res = StockUser::find_by_id(uid).one(db).await?;
    let model = res.unwrap();
    let mut entity = model.clone().into_active_model();

    let m = Decimal::from_f64_retain(money).unwrap();
    entity.usable_money = Set(model.usable_money + m);
    entity.update(db).await
}

/// 扣除冻结金额
pub async fn update_money_by_trade_buy(
    db: &DbConn,
    uid: i32,
    money: f64,
) -> Result<stock_user::Model, DbErr> {
    let res = StockUser::find_by_id(uid).one(db).await?;
    let model = res.unwrap();
    let mut entity = model.clone().into_active_model();

    let m = Decimal::from_f64_retain(money).unwrap();
    entity.disable_money = Set(model.disable_money + m);
    entity.update(db).await
}

// 交易
pub async fn update_money_by_trade(
    db: &DbConn,
    uid: i32,
    money: f64,
) -> Result<stock_user::Model, DbErr> {
    let res = StockUser::find_by_id(uid).one(db).await?;
    let model = res.unwrap();
    let mut entity = model.clone().into_active_model();

    let m: Decimal = Decimal::from_f64_retain(money).unwrap();
    entity.disable_money = Set(model.disable_money + m);
    entity.usable_money = Set(model.usable_money - m);
    entity.update(db).await
}

pub async fn get_by_id(db: &DbConn, id: i32) -> Result<Option<stock_user::Model>, DbErr> {
    StockUser::find_by_id(id).one(db).await
}
pub async fn add(
    db: &DbConn,
    model: stock_user::Model,
) -> Result<InsertResult<stock_user::ActiveModel>, DbErr> {
    let user: stock_user::ActiveModel = model.into();
    StockUser::insert(user).exec(db).await
}

pub async fn delete(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
    StockUser::delete_by_id(id).exec(db).await
}
pub async fn get_page(
    db: &DbConn,
    search: UserSearch,
) -> Result<(Vec<stock_user::Model>, u64), DbErr> {
    let mut query = StockUser::find();

    query = match search.uid {
        Some(value) => query.filter(stock_user::Column::Id.eq(value)),
        None => query,
    };

    query = match search.username {
        Some(value) => query.filter(stock_user::Column::Username.contains(&value)),
        None => query,
    };

    let page = query
        .order_by_desc(stock_user::Column::Created)
        .paginate(db, search.pagesize);

    let num_pages = page.num_pages().await?;
    page.fetch_page(search.pageindex - 1)
        .await
        .map(|p| (p, num_pages))
}
